package com.hongxun.design.utils.wifiutil;

import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import java.util.List;

import com.hongxun.design.BroadCastReceivers.WifiConnectBroadCast;
import com.hongxun.design.BroadCastReceivers.WifiStateBroadCast;
import com.hongxun.design.MyApp;
import com.hongxun.design.mytools.MyLog;


/**
 * Created by zerdoor_pc on 2016/4/18.
 */
public class WifiHostConnect {
    private static WifiHostConnect instance = null;
    private Context context;
    private String mSSID;
    private WifiStateBroadCast.WifiBroadCastOperations operations;
    public boolean isConnecting;
    private WifiConnectBroadCast wifiConnectReceiver;

    WifiHostConnect(Context context) {
        this.context = context;
        this.operations = (WifiStateBroadCast.WifiBroadCastOperations) context;

    }

    public static WifiHostConnect getInstance(Context context) {

        if (instance == null) {
            instance = new WifiHostConnect(context);
        }
        instance.context = context;
        return instance;
    }

    public void clear(){
        instance=null;
    }
    // 连接热点
    public void connectToHotpot(final String SSID, List<ScanResult> wifiList, final String password) {
//		if (isConnecting&&checkConnectHotIsEnable(SSID,wifiList))
        MyApp.isServer=false;
        if (SSID == null || SSID.equals("")) {
            MyLog.L(MyApp.AppName + "WIFI ssid is null or ");
            return;
        }
        if (SSID.equalsIgnoreCase(mSSID) && isConnecting) {
            MyLog.L(MyApp.AppName + "same ssid is  connecting!");
            operations.disPlayWifiConResult(false, null);
            return;
        }
        if (!checkConnectHotIsEnable(SSID, wifiList)) {
            MyLog.L(MyApp.AppName + "ssid is not in the wifiList!");
            operations.disPlayWifiConResult(false, null);
            return;
        }
        if (!WifiHostUtil.getInstance(context).wifiIsOpen()) {
            WifiHostSearch.getInstance(context).registerWifiStateBroadcast(SSID);
            WifiHostSearch.getInstance(context).wifiStateReceiver.setOpType(OpretionsType.CONNECT);
            WifiHostUtil.getInstance(context).openWifi();
        } else {
            enableNetwork(SSID, password);
        }
    }

    // 连接热点
    public void enableNetwork(final String SSID, final String password) {
        deleteMoreCon(SSID);
        MyLog.L(MyApp.AppName + "into enableNetwork(WifiConfiguration wifiConfig)");
        new Thread(new Runnable() {
            @Override
            public void run() {
                WifiConfiguration config = createWifiNoPassInfo(SSID, password);
                isConnecting = connectHotSpot(config);
                registerWifiConnectBroadCast();
                mSSID = SSID;
                if (!isConnecting) {
                    operations.disPlayWifiConResult(false, null);
                    MyLog.L(MyApp.AppName + "into enableNetwork(WifiConfiguration wifiConfig) isConnecting =" + isConnecting);
                    return;
                }
            }
        }).start();
        MyLog.L(MyApp.AppName + "out enableNetwork(WifiConfiguration wifiConfig)");
    }

    /* 连接热点 */
    private boolean connectHotSpot(WifiConfiguration wifiConfig) {
        MyLog.L(MyApp.AppName + "into enableNetwork(WifiConfiguration wifiConfig)");
        int wcgID = WifiHostUtil.getInstance(context).mWifimanager.addNetwork(wifiConfig);
        MyLog.L(MyApp.AppName + "into enableNetwork(WifiConfiguration wifiConfig) wcID = " + wcgID);
        if (wcgID < 0) {
            MyLog.L(MyApp.AppName + "into enableNetwork(WifiConfiguration wifiConfig) addNetWork fail!");
            operations.disPlayWifiConResult(false, null);
            return false;
        }
        boolean flag = WifiHostUtil.getInstance(context).mWifimanager.enableNetwork(wcgID, true);
        MyLog.L(MyApp.AppName + "out enableNetwork(WifiConfiguration wifiConfig)");
        return flag;
    }

    // 检查连接SSID是否在搜索到的wifi列表中
    public boolean checkConnectHotIsEnable(String wifiName, List<ScanResult> wifiList) {

        for (ScanResult result : wifiList) {
            if (result.SSID.contains(wifiName)) {
                return true;
            }
        }
        return false;
    }

    // 关闭重复的热点，避免连接不上
    public void deleteMoreCon(String SSID) {
        WifiManager mWifimanager = WifiHostUtil.getInstance(context).mWifimanager;
        MyLog.L(MyApp.AppName + "into deleteMoreCon(String SSID) SSID= " + SSID);
        String destStr = "\"" + SSID + "\"";
        MyLog.L(MyApp.AppName + "connectConfig  SSID= " + destStr);
        List<WifiConfiguration> existingConfigs = mWifimanager.getConfiguredNetworks();
        if (existingConfigs == null) {
            return;
        }
        for (WifiConfiguration existingConfig : existingConfigs) {
            MyLog.L(MyApp.AppName + "existingConfig SSID = " + existingConfig.SSID);
            if (existingConfig.SSID.equalsIgnoreCase(destStr)) {
                MyLog.L(MyApp.AppName + "existingConfig contain SSID = " + existingConfig.SSID);
                mWifimanager.disableNetwork(existingConfig.networkId);
                mWifimanager.removeNetwork(existingConfig.networkId);
            }
        }
        mWifimanager.saveConfiguration();
        MyLog.L(MyApp.AppName + "out deleteMoreCon(String SSID) SSID= " + SSID);

    }

    // 没有密码的情况
    public static WifiConfiguration createWifiNoPassInfo(String SSID, String password) {

        MyLog.L(MyApp.AppName + "into nopass  SSID = " + SSID + "  Password = " + password + " Type = ");
        WifiConfiguration config = new WifiConfiguration();
        config = createWifiInfo(config, SSID, password);
        // 千万别忘了转义字符
        config.wepKeys[0] = "\"" + "" + "\"";
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.wepTxKeyIndex = 0;
        config.status = WifiConfiguration.Status.ENABLED;
        MyLog.L(MyApp.AppName + "out nopass  SSID = " + SSID + "  Password = " + password + " Type = ");
        return config;
    }

    private static WifiConfiguration createWifiInfo(WifiConfiguration config, String SSID,
                                                    String password) {

        MyLog.L(MyApp.AppName + "into wifi热点连接配置   SSID = " + SSID + "  Password = " + password);
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        config.priority = 0;
        MyLog.L(MyApp.AppName + "into wifi热点连接配置   config.SSID = " + config.SSID + "  Password = " + password);
        return config;
    }


    // 注册wifi热点连接广播
    private void registerWifiConnectBroadCast() {
        if (wifiConnectReceiver == null) {
            wifiConnectReceiver = new WifiConnectBroadCast(operations);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        context.registerReceiver(wifiConnectReceiver, filter);
    }
    // 去掉wifi连接广播监听
    public void unRegisterWifiConnectBroadCast() {
        if (wifiConnectReceiver != null) {
            try {

                context.unregisterReceiver(wifiConnectReceiver);
            }catch (Exception e){}
            wifiConnectReceiver = null;
        }
    }
    //设置连接状态
    public void setConnectStatu(boolean connecting) {
        this.isConnecting = connecting;
    }


}
